package com.qth.valet.common.advice;

import com.qth.valet.common.exception.NoAuthException;
import com.qth.valet.common.exception.PaymentException;
import com.qth.valet.common.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final int NO_AUTH_CODE = 401;

    @ExceptionHandler(NoAuthException.class)
    public ResponseResult<String> handler(NoAuthException e) {
        log.error("登录异常: {}", e.getMessage(), e);
        return ResponseResult.fail(NO_AUTH_CODE, e.getMessage());
    }

    @ExceptionHandler(PaymentException.class)
    public ResponseResult<String> handler(PaymentException e) {
        log.error("订单异常: {}", e.getMessage(), e);
        return ResponseResult.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<String> handler(MethodArgumentNotValidException e) {
        log.error("参数异常: {}", e.getMessage(), e);
        return ResponseResult.fail(Objects.requireNonNull(e.getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseResult<String> handler(RuntimeException e) {
        log.error("运行时异常: {}", e.getMessage(), e);
        return ResponseResult.fail(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseResult<String> handler(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return ResponseResult.fail("系统异常");
    }

}
